using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using HollywoodHackers.Storage.Queue;
using HollywoodHackers.Storage.Table;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace HollywoodHackers.Web.Controllers
{
    public class SystemMessageController : Controller
    {
        UserNotificationRepository toastRepository;

        public SystemMessageController()
        {
            StorageAccountInfo tableAccount = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
            toastRepository = new UserNotificationRepository(null, null,
                tableAccount);
        }
        public ActionResult Create()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(SystemMessage message)
        {
            SystemMessageRepository repo = new SystemMessageRepository(QueueNames.SystemMessages);
            message.Title = "Test";
            repo.EnqueueSystemMessage(message);
            return RedirectToAction("Index");
        }

        public ActionResult Index()
        {
            /*SystemMessageRepository repo = new SystemMessageRepository(QueueNames.SystemMessages, false);
            IEnumerable<SystemMessage> messages = repo.GetMessages();
            return View(messages); */
            return null;
        }

        public ActionResult Clear()
        {
            SystemMessageRepository repo = new SystemMessageRepository(QueueNames.SystemMessages);
            repo.ClearMessages();
            return RedirectToAction("Index");
        }

        public JsonResult GetMessages()
        {
            if (User.Identity.IsAuthenticated)
            {
                UserTextNotification[] userToasts = toastRepository.GetNotifications(User.Identity.Name);
                object[] data = (from UserTextNotification toast in userToasts
                                 select new { title = toast.Title ?? "Notification", text = toast.MessageText }).ToArray();
                
                return Json(data);
            }
            else
                return Json(null);
        }
    }
}
